package down.xiaoheihe.work.Controller;

import down.xiaoheihe.work.Entity.User;
import down.xiaoheihe.work.Entity.UserExample;
import down.xiaoheihe.work.Mapper.UserMapper;
import down.xiaoheihe.work.Service.CacheService;
import down.xiaoheihe.work.Service.MailService;
import down.xiaoheihe.work.utils.CurPool;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@RestController
@MapperScan("down.xiaoheihe.work.Mapper")
@CrossOrigin
public class LoginLogout {
    @Autowired
    CacheService cacheService;
    @Autowired
    UserMapper tUserMapper;
    @Autowired
    MailService mailService;

    @PostMapping("/logout")
    public void 登出() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }
    @PostMapping("/login")
    public String 手机端登录(@RequestBody Map<String, String> data, HttpServletResponse response) {
        String username = data.get("username");
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username).andIsDeleteEqualTo(0);
        List<User> tUsers = tUserMapper.selectByExample(userExample);
        if (tUsers.size() == 0) {
            response.setStatus(405);
            return "找不到该会员！";
        }
        User tUser = tUsers.get(0);
        String password = data.get("password");
        Integer uid = tUser.getUid();
        UsernamePasswordToken token = new UsernamePasswordToken(String.valueOf(uid), password);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            //更新用户登录时间戳
            User user = new User();
            user.setUid(uid);
            user.setLatestLogin(new Date());
            tUserMapper.updateByPrimaryKeySelective(user);
            return "Login Success";
        } catch (IncorrectCredentialsException e) {
            response.setStatus(406);
            return "输入的密码有误";
        }
    }
    @GetMapping("/getSalt/{username}")
    public String getSalt (@PathVariable String username,HttpServletResponse response){
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username).andIsDeleteEqualTo(0);
        List<User> tUsers = tUserMapper.selectByExample(userExample);
        if (tUsers.size() == 0) {
            response.setStatus(405);
            return "找不到该用户！";
        }else {
            for (User user : tUsers) {
                String salt = user.getSalt();
                return salt;
            }
        }
        return "Null";
    }
    @PostMapping("/login2")
    public String 后台管理系统登录(@RequestBody Map<String, String> data, HttpServletResponse response) {
        String username = data.get("username");
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username).andIsAdministratorEqualTo(1).andIsDeleteEqualTo(0);
        List<User> tUsers = tUserMapper.selectByExample(userExample);
        if (tUsers.size() == 0) {
            response.setStatus(405);
            return "找不到该管理员！";
        }
        User tUser = tUsers.get(0);
        String password = data.get("password");
        Integer uid = tUser.getUid();
        UsernamePasswordToken token = new UsernamePasswordToken(String.valueOf(uid), password);
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return "Login Success";
        } catch (IncorrectCredentialsException e) {
            response.setStatus(406);
            return "输入的密码有误";
        }
    }
    @PostMapping("/register")
    public String 注册(@RequestBody Map<String, String> data, HttpServletResponse response) {
        String mail = data.get("mail");
        UserExample userExampleMail = new UserExample();
        userExampleMail.createCriteria().andEmailEqualTo(mail);
        List<User> mails = tUserMapper.selectByExample(userExampleMail);
        if (mails.size() != 0) {
            response.setStatus(408);
            return "该邮箱已经被人使用了！";
        }
        String username = data.get("username");
        UserExample userExample = new UserExample();
        userExample.createCriteria().andUsernameEqualTo(username);
        List<User> users = tUserMapper.selectByExample(userExample);
        if (users.size() != 0) {
            response.setStatus(405);
            return "该用户名已经被注册了！";
        }
        String password = data.get("password");
        String salt = data.get("salt");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setSalt(salt);
        user.setEmail(mail);
        tUserMapper.insertSelective(user);
        return "OK";
    }
    @GetMapping("/user")
    public User getUserById(@RequestParam Integer id) {
        return tUserMapper.selectByPrimaryKey(id);
    }
    @PostMapping("/fsyzm")
    public String 发送验证码(@RequestBody Map<String, String> data, HttpServletResponse response) {
        String mail = data.get("mail");
        UserExample userExample = new UserExample();
        userExample.createCriteria().andEmailEqualTo(mail);
        List<User> users = tUserMapper.selectByExample(userExample);
        if (users.size() == 0) {
            response.setStatus(405);
            return "找不到邮箱为此的会员！";
        }
        String yanzhengma = "";
        for (int i =
             0; i < 6; i++) {
            char ch = CurPool.str.charAt(new Random().nextInt(CurPool.str.length()));
            yanzhengma += ch;
        }
        try {
            mailService.sendHtmlMail(mail, yanzhengma);
            cacheService.add(mail, yanzhengma, 1, TimeUnit.MINUTES);
        } catch (MessagingException e) {
            response.setStatus(406);
            return "验证码发送失败！";
        }
        return "OK";
    }
    @PostMapping("/yanzheng")
    public String 验证码(@RequestBody Map<String, String> data, HttpServletResponse response) {
        String mail = data.get("mail");
        String pasw = data.get("pasw");
        String code = cacheService.get(mail);
        String substring = code.substring(1, code.length() - 1);
        if (pasw.equals(substring)) {
            UserExample userExample = new UserExample();
            userExample.createCriteria().andEmailEqualTo(mail);
            List<User> users = tUserMapper.selectByExample(userExample);
            for (User user : users) {
                user.setSalt("37");
                user.setPassword("6b7bc5d210b07f67b48bebbf626f7a74");
                tUserMapper.updateByPrimaryKeySelective(user);
            }
            return "OK";
        } else {
            response.setStatus(405);
            return "验证码错误";
        }
    }
}
